package com.bac.rentmap.ad.flat.proccess;

import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.bac.rentmap.ad.batch.proccess.BatchProccessor;
import com.bac.rentmap.jdo.JdoSupport;

public abstract class AbstractOldItemProcessor<T> extends JdoSupport implements
        BatchProccessor {
    private static final Logger log = Logger
            .getLogger(AbstractOldItemProcessor.class.getName());

    private Integer maxAgeInDays = -1;
    private int batchSize = 20;

    public int proccess() throws IOException {
        PersistenceManager persistenceManager = getPersistenceManager();
        try {
            Query query = persistenceManager.newQuery(getPersistentClass());
            Calendar calendar = GregorianCalendar.getInstance();
            calendar.add(Calendar.DATE, -maxAgeInDays);
            query.setFilter(getDatePropertyName() + " < publishingDateParam");
            query.setRange(0, batchSize);
            query.declareParameters("java.util.Date publishingDateParam");
            List<T> res = (List<T>)query.execute(calendar.getTime());
            for(T t: res){
                beforeDelete(t);
                persistenceManager.deletePersistent(t);
            }
            return res.size();
        } finally {
            persistenceManager.close();
        }
    }

    protected void beforeDelete(T t){

    }

    protected abstract Class<T> getPersistentClass();

    protected abstract String getDatePropertyName();

    public void setMaxAgeInDays(Integer maxAgeInDays) {
        this.maxAgeInDays = maxAgeInDays;
    }

    public int getQueueSize() {
        return -1;
    }

    public int getBatchSize() {
        return batchSize;
    }

    public void setBatchSize(int batchSize) {
        this.batchSize = batchSize;
    }
}
